package com.moore.utils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class JDBCUtils {
    public static String driver;
    public static String url;
    public static String username;
    public static String password;
    static{
        InputStream inputStream;
        try {
            inputStream = Files.newInputStream(Paths.get("conf/db.properties"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Properties properties = new Properties();
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        url = properties.getProperty("url");
        driver = properties.getProperty("driver");
        username = properties.getProperty("username");
        password = properties.getProperty("password");
    }
    private JDBCUtils(){}
    private static JDBCUtils instance = null;

    public synchronized static JDBCUtils getInstance() {
        if (instance == null) {
            instance = new JDBCUtils();
        }
        return instance;
    }

    public static Connection getConnection() throws Exception{
        Class.forName(driver);
        return DriverManager.getConnection(url, username, password);
    }
    public static List<String> executeSelect(String sql, String... args) throws Exception{
        List<String> list = new ArrayList<>();
        Connection conn = getConnection();
        Statement st = conn.createStatement();
        ResultSet rs = st.executeQuery(sql);
        while (rs.next()) {
            for (String arg : args) {
                list.add(rs.getString(arg));
            }
        }
        close(rs, st, null, conn);
        return list;
    }
    public static int executeUpdate(String sql, Object... args) throws Exception {
        Connection conn = getConnection();
        PreparedStatement ps = conn.prepareStatement(sql);
        for (int i = 0; i < args.length; i++) {
            ps.setObject(i + 1, args[i]);
        }
        int result = ps.executeUpdate(); // 先执行更新操作
        close(null, null, ps, conn); // 然后关闭资源
        return result;
    }
    public static void close(ResultSet rs, Statement st, PreparedStatement ps,Connection conn) {
        try {
            if (rs != null)
                rs.close();
            if (st != null)
                st.close();
            if (ps != null)
                ps.close();
            if (conn != null)
                conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
